#!/usr/bin/env python3
# Author:liang futing
#@Time :2020/3/8 8:48
from PIL import Image,ImageDraw,ImageFont
from io import BytesIO
import random


def get_random_color():
    return (random.randint(0, 255),
            random.randint(0, 255),
            random.randint(0, 255))

def get_validcode(request):
    '''
    返回验证码图片
    '''

    # 方式1   图片是写死的
    # with open('luff.jpg','rb') as f:
    #     data=f.read()

    # 方式2 pillow + disk


    # from PIL import Image
    # img = Image.new("RGB",(270, 36),color=get_random_color())
    # with open('validCode.png',"wb",) as f :
    #     img.save(f,'png')
    # with open('validCode.png','rb') as f:
    #     data=f.read()

    # 方式3 pillow + memory
    # from PIL import Image
    # from io import BytesIO
    # img = Image.new("RGB",(270, 36),color=get_random_color())
    # f=BytesIO()
    # img.save(f,'png')
    # data=f.getvalue()

    # 方式4 pillow + memory+验证码

    img = Image.new("RGB", (270, 36), color=get_random_color())
    draw=ImageDraw.Draw(img)
    kumo_font=ImageFont.truetype('static/font/kumo.ttf',size=32)
    #draw可以划点，划线，写文本
    # draw.text()
    # draw.line()
    # draw.point()
    # 写验证码
    valid_code_str = ''
    for i in range(5):
        random_num = str(random.randint(0,9))
        random_low_alpha = chr(random.randint(97,122))
        random_upper_alpha = chr(random.randint(65,90))
        random_char = random.choice([random_num,random_low_alpha,random_upper_alpha])
        valid_code_str += random_char
        draw.text((i*45+30, 5), random_char, get_random_color(), font=kumo_font)


    # 画噪点噪线,暂时先不用这个功能
    # width = 270
    # height = 36
    # for i in range(10):
    #     x1=random.randint(0,width)
    #     x2=random.randint(0,width)
    #     y1=random.randint(0,height)
    #     y2=random.randint(0,height)
    #     draw.line((x1,y1,x2,y2),fill=get_random_color(),)
    # for i in range(50):
    #     draw.point([random.randint(0,width),random.randint(0,height)],
    #                fill=get_random_color())
    #     x=random.randint(0,width)
    #     y=random.randint(0,height)
    #     draw.arc((x,y,x+4,y+4),0,90,fill=get_random_color())
    # print(valid_code_str)
    request.session['valid_code_str']=valid_code_str
    # 写入内存，然后从内存返回
    f = BytesIO()
    img.save(f, 'png')
    data = f.getvalue()
    return data
